//
//  TalkViewController.m
//  Shine
//
//  Created by 王斌 on 16/3/9.
//  Copyright © 2016年 王斌. All rights reserved.
//

#import "TalkViewController.h"
#import "JoinViewController.h"
#import "MJRefresh.h"
#import "UserProfileManager.h"
#import "MessageViewController.h"
#import "CallViewController.h"
//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@interface TalkViewController ()<UITableViewDataSource, UITableViewDelegate, IChatManagerDelegate, EMCallManagerDelegate>

@property (nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)NSArray *listArr;

@property(nonatomic, strong)UIButton *joinButton;

@property (nonatomic, strong) MJRefreshLegendHeader *header;

@property (nonatomic, strong) EMPushNotificationOptions *options;

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation TalkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加观察者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(joinButtonTitleChange:) name:@"LoggedIn" object:nil];
    
    // 创建视图
    [self createView];

    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"AutoJoin"] isEqualToString:@"Yes"]) {
        // 自动登陆
        [self autoJoin];
    }
    
    /**
     *  注册Delegate
     */
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].callManager removeDelegate:self];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    
    // Do any additional setup after loading the view from its nib.
}

// 添加MBprogressHUD
- (void)showHUD
{
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:self.userName password:self.passWord];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"登陆中~";
}

// 注销MBprogressHUD
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [self.HUD removeFromSuperview];
    self.HUD = nil;
}



/*!
 @method
 @brief 用户登录后的回调
 @discussion
 @param loginInfo 登录的用户信息
 @param error     错误信息
 @result
 */
- (void)didLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error{
    if (!error) {
        JoinViewController *join = [[JoinViewController alloc] init];
        [join dismissViewControllerAnimated:YES completion:^{
            
        }];
        [self hudWasHidden:self.HUD];
        self.header = [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(createData) dateKey:@"find"];
        [self.header beginRefreshing];
        self.options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
        [self createData];
        [[NSUserDefaults standardUserDefaults]setObject:loginInfo[@"username"] forKey:@"userName"];
        [[NSUserDefaults standardUserDefaults]setObject:loginInfo[@"password"] forKey:@"passWord"];
        //
        NSNotification *notification =[NSNotification notificationWithName:@"LoggedIn" object:nil userInfo:[NSDictionary dictionaryWithObject:@"退出" forKey:@"LoggedIn"]];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        [[NSUserDefaults standardUserDefaults] setObject:@"Yes" forKey:@"AutoJoin"];

    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            JoinViewController *join = [[JoinViewController alloc] init];
            [self presentViewController:join animated:YES completion:^{
                
            }];
        }];
        [alertController addAction:alert];
        [self presentViewController:alertController animated:YES completion:^{
            
        }];

    }
}

/*!
 @method
 @brief 收到消息时的回调
 @param message      消息对象
 @discussion 当EMConversation对象的enableReceiveMessage属性为YES时, 会触发此回调
 针对有附件的消息, 此时附件还未被下载.
 附件下载过程中的进度回调请参考didFetchingMessageAttachments:progress:,
 下载完所有附件后, 回调didMessageAttachmentsStatusChanged:error:会被触发
 */
- (void)didReceiveMessage:(EMMessage *)message{
    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = NSLocalizedString(@"message.video", @"Video");
            }
                break;
            default:
                break;
        }
        
        NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
        if (message.messageType == eMessageTypeGroupChat) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:message.conversationChatter]) {
                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                    break;
                }
            }
        }
        else if (message.messageType == eMessageTypeChatRoom)
        {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
            if (chatroomName)
            {
                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
            }
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
//    notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
    } else {
        notification.soundName = UILocalNotificationDefaultSoundName;
        self.lastPlaySoundDate = [NSDate date];
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
    notification.userInfo = userInfo;
    
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//        UIApplication *application = [UIApplication sharedApplication];
//        application.applicationIconBadgeNumber += 1;

}

/*!
 @method
 @brief 更新消息推送相关属性配置(异步方法)
 @param options    属性
 @param completion 回调
 @param aQueue     回调时的线程
 @result
 */
- (void)asyncUpdatePushOptions:(EMPushNotificationOptions *)options
                    completion:(void (^)(EMPushNotificationOptions *options, EMError *error))completion
                       onQueue:(dispatch_queue_t)aQueue{
    
}

/**
 *  获取好友列表
 */
- (void)createData{
    [self.header endRefreshing];
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        if (!error) {
            self.listArr = [NSArray arrayWithArray:buddyList];
            [self.tableView reloadData];
        }
    } onQueue:nil];
}

// 接收到好友请求时的回调
- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@想添加您为好友", username] message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertSure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        EMError *error = nil;
        BOOL isSuccess = [[EaseMob sharedInstance].chatManager acceptBuddyRequest:username error:&error];
        __weak typeof (self)weakSelf = self;
        if (isSuccess && !error) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"添加成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 点击确定 刷新好友列表
                [weakSelf createData];
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            
        }
    }];
    UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        EMError *error = nil;
        BOOL isSuccess = [[EaseMob sharedInstance].chatManager rejectBuddyRequest:username reason:@"对方拒绝了您的请求" error:&error];
        if (isSuccess && !error) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"拒绝成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            
        }
    }];
    [alertController addAction:alertCancel];
    [alertController addAction:alertSure];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    

}


/*!
 @method
 @brief 好友请求被接受时的回调
 @discussion
 @param username 之前发出的好友请求被用户username接受了
 */
- (void)didAcceptedByBuddy:(NSString *)username{
    __weak typeof (self)weakself = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"添加好友成功" message:[NSString stringWithFormat:@"%@ 已通过您的好友验证", username] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself createData];
    }];
    [alertController addAction:alert];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];

}

/*!
 @method
 @brief 好友请求被拒绝时的回调
 @discussion
 @param username 之前发出的好友请求被用户username拒绝了
 */
- (void)didRejectedByBuddy:(NSString *)username{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"添加好友失败" message:[NSString stringWithFormat:@"%@ 已拒绝您的好友验证", username] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];
    [alertController addAction:alert];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}


- (void)joinButtonTitleChange:(NSNotification *)notification{
    [self.joinButton setTitle:notification.userInfo[@"LoggedIn"] forState:UIControlStateNormal];
}

- (void)autoJoin{
    NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
    NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:@"passWord"];
    BOOL isAutoLogin = [[EaseMob sharedInstance].chatManager isAutoLoginEnabled];
    if (!isAutoLogin) {
        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:userName password:passWord];
        self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.HUD.labelText = @"自动登录中~";
//        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:userName password:passWord completion:^(NSDictionary *loginInfo, EMError *error) {
//            if (!error) {
//                NSNotification *notification = [NSNotification notificationWithName:@"LoggedIn" object:nil userInfo:[NSDictionary dictionaryWithObject:@"退出" forKey:@"LoggedIn"]];
//                [[NSNotificationCenter defaultCenter] postNotification:notification];
//                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登陆成功" message:@"已自动登陆" preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    
//                }];
//                [alertController addAction:alert];
//                [self presentViewController:alertController animated:YES completion:^{
//                    
//                }];

//            }else{
//                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    
//                }];
//                [alertController addAction:alert];
//                [self presentViewController:alertController animated:YES completion:^{
//                    
//                }];
//                
//            }
//            
//        } onQueue:nil];
    }
}

- (void)addFriends{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"添加好友" message:@"请输入账号" preferredStyle:UIAlertControllerStyleAlert];
    // 添加textField
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入要查找的账号:";
        
    }];
    
    UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 点击获取textField里的内容
        UITextField *text = [alertController.textFields firstObject];
        NSString *account = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
        EMError *error = nil;
        BOOL isSuccess = [[EaseMob sharedInstance].chatManager addBuddy:text.text message:@"我想加您为好友" error:&error];
        if (isSuccess && !error && text.text.length != 0 && ![text.text isEqualToString:account]) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"添加成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];

        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
            
        }
    }];
    UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:alertCancel];
    [alertController addAction:alert];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];

}

#pragma mark 创建视图
- (void)createView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN, HEIGHT_SCREEN) style:UITableViewStylePlain];
    self.tableView.rowHeight = 80;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"talkReuse"];
    
    self.joinButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.joinButton.frame = CGRectMake(0, 0, 40, 40);
    [self.joinButton setTitle:@"登陆" forState:UIControlStateNormal];
    [self.joinButton addTarget:self action:@selector(joinButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *headButton = [UIButton buttonWithType:UIButtonTypeCustom];
    headButton.frame = CGRectMake(0, 0, 50, 50);
    [headButton addTarget:self action:@selector(headButton:) forControlEvents:UIControlEventTouchUpInside];
    headButton.layer.cornerRadius = 25;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headButton];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.joinButton];
}

/**
 *  头像设置
 *
 *  @return nil
 */
- (void)headButton:(UIButton *)button{
    
}

#pragma mark 登陆按钮
- (void)joinButton:(UIButton *)button{
    if ([button.titleLabel.text isEqualToString:@"登陆"]) {
        JoinViewController *joinVC = [[JoinViewController alloc] init];
        [self presentViewController:joinVC animated:YES completion:^{
            
        }];
        
    }else{
        [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
            if (!error && !info) {
                
                NSNotification *notification = [NSNotification notificationWithName:@"LoggedIn" object:nil userInfo:[NSDictionary dictionaryWithObject:@"登陆" forKey:@"LoggedIn"]];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                
                [[NSUserDefaults standardUserDefaults]setObject:@"No" forKey:@"AutoJoin"];
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"已退出登陆" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:alert];
                [self presentViewController:alertController animated:YES completion:^{
                    
                }];

            }else{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:alert];
                [self presentViewController:alertController animated:YES completion:^{
                    
                }];
                
            }
        } onQueue:nil];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return self.listArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UILabel *titleLabe = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, WIDTH_SCREEN, 20)];
        titleLabe.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.0];
        titleLabe.text = @"     好友";
        return titleLabe;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"talkReuse" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.imageView.image = [UIImage imageNamed:@"group_creategroup"];
        cell.textLabel.text = @"添加好友";
//        }else{
//            cell.imageView.image = [UIImage imageNamed:@"group_header"];
//            cell.textLabel.text = @"群组";
//        }
        return cell;
    }else{
        EMBuddy *buddy = self.listArr[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:@"chatListCellHead"];
        cell.textLabel.text = buddy.username;
        return cell;
    }
}

#pragma mark tableview点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self addFriends];
        }
    }else{
        EMBuddy *buddy = self.listArr[indexPath.row];
        MessageViewController *chatController = [[MessageViewController alloc] initWithConversationChatter:buddy.username conversationType:eConversationTypeChat];
        [self.navigationController pushViewController:chatController animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 设置tableview的编辑
// 左滑添加按钮
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *actionSecond = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        EMError *error = nil;
        EMBuddy *buddy = self.listArr[indexPath.row];
        // 删除好友
        BOOL isSuccess = [[EaseMob sharedInstance].chatManager removeBuddy:buddy.username removeFromRemote:YES error:&error];
        if (isSuccess && !error) {
            [self createData];
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"错误" message:error.description preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:alert];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];

        }
    }];
    NSArray *arr = @[actionSecond];
    
    return arr;
}

#pragma mark  逐行的去设置,哪些行编辑,哪些行不编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    }else{
        return YES;
    }
}


- (void)callOutWithChatter:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (![self canRecord]) {
            return;
        }
        
        EMError *error = nil;
        NSString *chatter = [object objectForKey:@"chatter"];
        EMCallSessionType type = [[object objectForKey:@"type"] intValue];
        EMCallSession *callSession = nil;
        if (type == eCallSessionTypeAudio) {
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:chatter timeout:50 error:&error];
        }
        else if (type == eCallSessionTypeVideo){
            if (![CallViewController canVideo]) {
                return;
            }
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:chatter timeout:50 error:&error];
        }
        
        if (callSession && !error) {
//            [[EaseMob sharedInstance].callManager removeDelegate:self];
            CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:NO];
            callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:callController animated:NO completion:nil];
        }
        
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"error") message:error.description delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
}

- (void)callControllerClose:(NSNotification *)notification
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

#pragma mark 实时通话协议方法
- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error
{
    if (callSession.status == eCallSessionStatusConnected)
    {
        EMError *error = nil;
        do {
            BOOL isShowPicker = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isShowPicker"] boolValue];
            if (isShowPicker) {
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
            if (![self canRecord]) {
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
#warning 在后台不能进行视频通话
            if(callSession.type == eCallSessionTypeVideo && ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive || ![CallViewController canVideo])){
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
            if (!isShowPicker){
//                [[EaseMob sharedInstance].callManager removeDelegate:self];
                CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:YES];
                callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:callController animated:NO completion:nil];
                //                if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]])
                //                {
                //                    ChatViewController *chatVc = (ChatViewController *)self.navigationController.topViewController;
                //                    chatVc.isViewDidAppear = NO;
                //                }
            }
        } while (0);
        
        if (error) {
            [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReasonHangup];
            return;
        }
    }
}

#pragma mark 实时通话
- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    if (!bCanRecord) {
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"setting.microphoneNoAuthority", @"No microphone permissions") message:NSLocalizedString(@"setting.microphoneAuthority", @"Please open in \"Setting\"-\"Privacy\"-\"Microphone\".") delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
        [alt show];
    }
    
    return bCanRecord;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
